package com.brid.careasy;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;

/**
 * @Author: 司军强
 * @Date 2020/2/20 10:28
 * @Description:
 */
@Slf4j
public class HttpPost {

    // in milliseconds  连接超时的时间
    private final static int CONNECT_TIMEOUT = 5000;


    //字符串编码
    private final static String DEFAULT_ENCODING = "UTF-8";


    /**
     * post数据请求
     *
     * @param urlStr      请求的路径
     * @param data        请求的数据
     * @param contentType 内容的格式   Content-Type: application/json
     * @return 响应的结果
     */
    public static String post(String urlStr, String data, String contentType, Integer timeout) {
        BufferedReader reader = null;
        try {
            //创建url实例
            URL url = new URL(urlStr);
            //获取连接通道
            URLConnection conn = url.openConnection();
            //设置连接url输出信息
            conn.setDoOutput(true);
            //设置连接超时时间
            conn.setConnectTimeout(timeout == null ? CONNECT_TIMEOUT : timeout);
            //设置读取资源时间
            conn.setReadTimeout(timeout == null ? CONNECT_TIMEOUT : timeout);
            //设置请求属性
            if (contentType != null)
                conn.setRequestProperty("content-type", contentType);
            //使用utf-8编码 进行将数据输出
            OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), DEFAULT_ENCODING);
            if (data == null)
                data = "";
            writer.write(data);
            writer.flush();
            writer.close();
            //读取返回的数据资源 使用utf-8
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), DEFAULT_ENCODING));
            //下面是读取资源和 关闭流
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            return sb.toString();
        } catch (IOException e) {
            log.info("Error connecting to " + urlStr + ": " + e.getMessage());
        } finally {
            try {
                if (reader != null)
                    reader.close();
            } catch (IOException e) {
                log.error(e.getMessage(),e);
             }
        }
        return null;
    }

}
